/* eslint-disable @typescript-eslint/no-unsafe-assignment */
// filters/http-exception.filter.ts
import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
  Logger,
} from '@nestjs/common';
import { Request, Response } from 'express';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  private readonly logger = new Logger(AllExceptionsFilter.name);

  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;
    const message: any =
      exception instanceof HttpException ? exception.getResponse() : exception;

    // 日志记录
    this.logger.error(
      `HTTP ${status} ${request.method} ${request.url} - ${JSON.stringify(message)}`,
    );

    response.status(status).json({
      // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
      code: message.code,
      // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
      message: message.message,
      path: request.url,
      timestamp: new Date().toISOString(),
    });
  }
}
